package com.stylefeng.guns.crawlers.zgzc;

import cn.wanghaomiao.seimi.annotation.Crawler;
import cn.wanghaomiao.seimi.def.BaseSeimiCrawler;
import cn.wanghaomiao.seimi.struct.Request;
import cn.wanghaomiao.seimi.struct.Response;
import com.stylefeng.guns.modular.business.service.IGameService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Element;
import org.seimicrawler.xpath.JXDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 北单数据爬虫
 *
 * @author wuchong
 */
@Slf4j
@Crawler(name = "updateBdCraw")
public class UpdateBdCrawler extends BaseSeimiCrawler {

    private static final String ZGZCW = "http://cp.zgzcw.com/";
    private static final long serialVersionUID = -6789561557459283755L;

    @Autowired
    private transient IGameService gameService;

    /**
     * @return 设置起始url
     */
    @Override
    public String[] startUrls() {
        return new String[]{ZGZCW + "lottery/bdplayvsforJsp.action?lotteryId=200&v=1224"};
    }

    /**
     * 针对startUrl生成首批的response回调这个初始接口
     *
     * @param response --
     */
    @Override
    public void start(Response response) {

        JXDocument jxDocument = response.document();
        // 查询已结束的比赛记录
        List<Object> matchTrs = jxDocument.sel("//table[@class='mb']/tbody/tr[@expire=\"0\"][@class=\"endBet hide\"]");
        List<Map<String, String>> results = matchTrs.stream().map(
                object -> {
                    Element element = (Element) object;
                    // 将tr数据转换为北单比赛内容
                    String mid = element.getElementsByClass("wh-10 b-l").get(0).attr("newplayid");
                    //实际比分
                    String actualScore = element.getElementsByClass("wh-5 bf").get(0).text();
                    if (actualScore.contains(":")) {
                        HashMap<String, String> map = new HashMap<>(4);
                        map.put("mid", mid);
                        map.put("score", StringUtils.trim(actualScore));
                        return map;
                    }
                    return null;

                }).filter(Objects::nonNull).collect(Collectors.toList());

        log.info("需要更新的比赛记录为={}", results);

        if (!results.isEmpty()) {
            gameService.updateGame(results);
        }
    }

    @Scheduled(cron = "0 0 */1 * * ?")
    public void callByCron() {
        logger.info("我是一个根据cron表达式执行的调度器，半小时一次");
        // 可定时发送一个Request
        push(Request.build(startUrls()[0], "start").setSkipDuplicateFilter(true));
    }

}
